package com.darth.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 
 * @author wangyajun.sdc 
 * @date 2018年6月20日 上午10:51:51
 * @version 1.0
 * 
 */
public class SignxfjhShaUtil {

    final static String ALGORITHM = "SHA-256";

    //第三方==幸福交行  secretKey=123456
    //	public static void main(String[] args) {
    //		String thirdSign = third();
    //		String xfjhSign = xfjh();
    //		if(thirdSign.equals(xfjhSign)) {
    //		    System.out.println("sign=====<"+thirdSign+">");
    //			System.out.println("校验通过");
    //		}else {
    //			System.out.println("校验faile");
    //		}
    //	}

    //第三方请求
    public static String third() {
        String message = "appKey=04abfc61f6ec47bda9016249478c5b21&authCode=9ddfcef2-1cec-42b6-a573-270593228a91&timestamp=1529995947524&secretKey=ec6fd5b5f70947188e60e2af058fe680";
        System.out.println(message);
        return jdkSha256(message);
    }

    //幸福交行
    public static String xfjh() {
        String secretKey = "ec6fd5b5f70947188e60e2af058fe680";
        String message = "appKey=04abfc61f6ec47bda9016249478c5b21&authCode=9ddfcef2-1cec-42b6-a573-270593228a91&timestamp=1529995947524&secretKey="
                + secretKey;
        return jdkSha256(message);
    }


    /**
     * 使用sha256 加密算法
     * @param message
     */
    public static String jdkSha256(String message) {

        try {
            MessageDigest sha256 = MessageDigest.getInstance(ALGORITHM);
            //加密密文
            byte[] sha256Encode = sha256.digest(message.getBytes());
            //System.out.println("加密后的密文："+convertByteToHexString(sha256Encode));
            return convertByteToHexString(sha256Encode);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * 将byte数组转换为16进制输出
     * @param bytes
     * @return
     */
    public static String convertByteToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < bytes.length; i++) {
            int temp = bytes[i] & 0xff;
            String tempHex = Integer.toHexString(temp);
            if (tempHex.length() < 2) {
                sb.append("0").append(tempHex);
            } else {
                sb.append(tempHex);
            }
        }
        return sb.toString();
    }

}
